import { Injectable } from '@nestjs/common';
import { createHash, randomUUID } from 'node:crypto'
import * as mqtt from "mqtt";
import { MqttClient } from 'mqtt';

@Injectable()
export class MqttClientService {

  md5(str:string) {
    return createHash('md5').update(str).digest('hex').toLowerCase()
  }


  client(url:string){
    const uuid = randomUUID()
    const username = this.md5((new Date()).toLocaleString())

    if(username.length < 9) throw new Error('username length can not less than 9');

    const p0 = username.slice(0, 4)
    const p1 = username.slice(4, username.length - 4)
    const p2 = username.slice(username.length - 4)

    const password = createHash('sha256').update(this.md5(p0) + this.md5(p1) + this.md5(p2)).digest('hex').toLowerCase()

    return mqtt.connect(url, {
      clientId: '$$' + uuid,
      username: username,
      password: password,
    })
    

    // return new Promise((reslove, reject) => {
    //   const client = mqtt.connect(url, {
    //     clientId: '$$' + uuid,
    //     username: username,
    //     password: password,
    //   })

    //   client.on('connect', () => {
    //     reslove(client)
    //   });

    //   client.on('error', res => {
    //     reject('mqtt 链接失败')
    //   })
    // })

  }

  
}
